package com.supply.hsa.sync.ean;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.supply.hsa.link.common.constant.InitConfigData;
import com.supply.hsa.sync.ean.model.*;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;

public class ApiServiceRapid {
	private Gson gson = new Gson();
	
	public static EANRapidConfig queryConfig(String supplyCode){
		EANRapidConfig config=new EANRapidConfig();
		Map<String, String> map= InitConfigData.shareSupplierMap.get(supplyCode);
		if(!map.isEmpty()){
			config.setRapidApikay(map.get(RapidConstants.RAPIDAPIKEY).toString());
			config.setRapidSignature(map.get(RapidConstants.RAPIDSIGNATURE).toString());
			config.setRapidURL(map.get(RapidConstants.RAPIDURL).toString());
			config.setLanguage(map.get(RapidConstants.LANGUAGE).toString());
			config.setCustomerIpAddress(map.get(RapidConstants.CUSTOMERIPADDRESS).toString());
		}
		/**
		 * 测试代码
		 */
//		config.setRapidApikay("iv05hip6l5d81qcm2fmr3dj8g");
//		config.setRapidSignature("epbm0bhrfq8ce");
//		config.setRapidURL("https://test.ean.com/2.2/");
//		config.setLanguage("en-US");
//		config.setCustomerIpAddress("19.168.0.145");
		return config;
	}
	
	
	private String getSignature(String apiKey, String sharedSecret){
		Date date= new Date();
		Long timestamp = (date.getTime() / 1000);
		
		String signature = null;
		try {
		   String toBeHashed = apiKey + sharedSecret + timestamp;
		   MessageDigest md = MessageDigest.getInstance("SHA-512");
		   byte[] bytes = md.digest(toBeHashed.getBytes("UTF-8"));
		   StringBuilder sb = new StringBuilder();
		   for(int i=0; i< bytes.length ;i++){
		       sb.append(Integer.toString((bytes[i] & 0xff) + 0x100, 16).substring(1));
		   }
		   signature = sb.toString();
		} catch (NoSuchAlgorithmException e) {
		   e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
		   e.printStackTrace();
		}
		String authHeaderValue = "EAN APIKey=" + apiKey +  ",Signature=" + signature + ",timestamp=" + timestamp;
		return authHeaderValue;
	}
	
	private String getJsonObject(BaseRequestRapid baseRequest, Map<String,Object> paramMap, String language){
		EANRapidConfig config=queryConfig(baseRequest.getSupplyCode());
		if(language != null){
			config.setLanguage(language);
		}
		StringBuffer urlRow=new StringBuffer(config.getRapidURL()+baseRequest.getParamURL()+"?language="+config.getLanguage());
		
		if(!paramMap.isEmpty()){
			for(String key:paramMap.keySet()){
				urlRow.append("&"+key+"=").append(paramMap.get(key));
			}
		}
		
		Map<String, String> headers = new HashMap<String, String>();
		headers.put("Authorization", getSignature(config.getRapidApikay(),config.getRapidSignature()));
		headers.put("Customer-Ip", config.getCustomerIpAddress());
		headers.put("Customer-Session-Id", UUID.randomUUID().toString());
		
		String result=EanHttpUtil.getForJsonGzip(urlRow.toString(), headers, baseRequest.getTimeOut());
		return result;
	}
	
	/**
	 * 查询区域下的所有区域节点
	 * @param regionId
	 * @param supplyCode
	 * @return
	 */
	public RegionDescendants queryRegions(String regionId, String supplyCode, String language){
		BaseRequestRapid baseRequest = new BaseRequestRapid();
		baseRequest.setParamURL("regions/"+regionId+"/descendants");
		baseRequest.setSupplyCode(supplyCode);
		
		Map<String,Object> paramMap = new IdentityHashMap<String,Object>(1);
		paramMap.put(new String("include"), "standard");
		RegionDescendants regionDescendants = new RegionDescendants();
		String result = getJsonObject(baseRequest, paramMap, language);
		
		Map<String, Map<String, Region>> regionMap= gson.fromJson(result, new TypeToken<Map<String, Map<String, Region>>>(){}.getType());
		regionDescendants.setRegionMap(regionMap);
		return regionDescendants;
	}
	
	/**
	 * 查询区域下的所有区域节点(含酒店id)
	 * @param regionId
	 * @param supplyCode
	 * @return
	 */
	public RegionDescendants queryHotelIds(String regionId, String supplyCode){
		BaseRequestRapid baseRequest = new BaseRequestRapid();
		baseRequest.setParamURL("regions/"+regionId+"/descendants");
		baseRequest.setSupplyCode(supplyCode);
		
		Map<String,Object> paramMap = new IdentityHashMap<String,Object>(2);
		paramMap.put(new String("include"), "details");
		paramMap.put(new String("include"), "property_ids");
		RegionDescendants regionDescendants = new RegionDescendants();
		String result = getJsonObject(baseRequest, paramMap, null);
		Map<String, Map<String, Region>> regionMap= gson.fromJson(result, new TypeToken<Map<String, Map<String, Region>>>(){}.getType());
		regionDescendants.setRegionMap(regionMap);
		return regionDescendants;
	}
	
	/**
	 * 根据酒店id查询酒店信息和房型数据
	 * @param hotelIds
	 * @param supplyCode
	 * @return
	 */
	public List<HotelInfo> queryHotel(List<String> hotelIds, String supplyCode, String language){
		BaseRequestRapid baseRequest = new BaseRequestRapid();
		baseRequest.setParamURL("properties/content");
		baseRequest.setSupplyCode(supplyCode);
		Map<String,Object> paramMap = new IdentityHashMap<String,Object>();
		if(!hotelIds.isEmpty()){
			for(String hotelId:hotelIds){
				paramMap.put(new String("property_id"), hotelId);
			}
		}
		
		String result = getJsonObject(baseRequest, paramMap, language);
		Map<String, PropertyContent> map= gson.fromJson(result, new TypeToken<Map<String, PropertyContent>>(){}.getType());
		if(map!=null){
			List<HotelInfo> contents=new ArrayList<HotelInfo>();
			for(String key:map.keySet()){
				PropertyContent hotel=map.get(key);
				
				HotelInfo hotelInfo=new HotelInfo();
				hotelInfo.setPropertyContent(hotel);
				if(hotel.getAddress()!=null){
					hotelInfo.setAddress1(hotel.getAddress().getLine_1());
					hotelInfo.setAddress2(hotel.getAddress().getLine_2());
					hotelInfo.setCity(hotel.getAddress().getCity());
					hotelInfo.setCountryCode(hotel.getAddress().getCountry_code());
					hotelInfo.setProvinceCode(hotel.getAddress().getState_province_code());
					hotelInfo.setProvinceName(hotel.getAddress().getState_province_name());
				}
				if(hotel.getCheckin()!=null){
					hotelInfo.setCheckin(hotel.getCheckin().getBegin_time());
				}
				if(hotel.getCheckout()!=null){
					hotelInfo.setCheckout(hotel.getCheckout().getTime());
				}
				
				hotelInfo.setFax(hotel.getFax());
				hotelInfo.setHotelId(hotel.getProperty_id());
				hotelInfo.setHotelName(hotel.getName());
				hotelInfo.setPhone(hotel.getPhone());
				hotelInfo.setRank(hotel.getRank());
				if(hotel.getLocation()!=null && hotel.getLocation().get("coordinates") !=null){
					hotelInfo.setLatitude(hotel.getLocation().get("coordinates").getLatitude());
					hotelInfo.setLongitude(hotel.getLocation().get("coordinates").getLongitude());
				}
			
				if(hotel.getRatings() != null && hotel.getRatings().getProperty()!=null){
					hotelInfo.setRating(hotel.getRatings().getProperty().getRating());
				}
				
				if(hotel.getRooms()!=null){
					List<RoomTypeInfo> roomTypeInfos= new ArrayList<RoomTypeInfo>();
					for(String key3:hotel.getRooms().keySet()){
						RoomContent roomContent=hotel.getRooms().get(key3);
						RoomTypeInfo roomTypeInfo = new RoomTypeInfo();
						if(roomContent.getBed_groups()!=null){
							String bedDesc="";
							for(String key4:roomContent.getBed_groups().keySet()){
								BedGroup bedGroup=roomContent.getBed_groups().get(key4);
								bedDesc=bedDesc+bedGroup.getDescription()+",";
							}
							roomTypeInfo.setBedDesc(bedDesc.substring(0, bedDesc.length()-1));
						}
						roomTypeInfo.setName(roomContent.getName());
						roomTypeInfo.setRoomTypeId(roomContent.getId());
						roomTypeInfos.add(roomTypeInfo);
					}
					hotelInfo.setRooms(roomTypeInfos);
				}
				
				contents.add(hotelInfo);
			}
			return contents;
		}
		return null;
	}
	
}
